//按用户自定义查询条件查询，调用datagird的load方法，传递name查询条件
function QueryData() {
    loadDataGrid(); 
}
//清除查询条件
function ClearQuery() {
    $(':input',theArgFormID)  
    .not(':button, :submit, :reset, :hidden')  
    .val('')  
    .removeAttr('checked')  
    .removeAttr('selected');  
}

$(function() {
	
	if(typeof theGridID != 'undefined'){
		$(theGridID).datagrid(
		{
			title : theGridTitle==''?'': "",
			align : 'center',
			width : document.body.clientWidth,
			height : document.body.clientHeight,
			fit:typeof theFit != 'undefined' ?theFit:true,
			fitColumns:typeof theFitColumns != 'undefined' ?theFitColumns:true,
			nowrap : false,
			striped : true,
			collapsible : false,
			url : '',
			sortName : theSortName,
			sortOrder : theSortOrder,
			remoteSort : false,
			idField : theIdField,
			loadMsg : '正在努力加载数据，请稍后...',
			singleSelect:typeof theSingleSelect != 'undefined' ?theSingleSelect:true,//是否单选 
			pagination : typeof thePagination != 'undefined' ?thePagination:true,//是否显示分页工具栏
			rownumbers : typeof theRownumbers != 'undefined' ?theRownumbers:true,
			pageSize:10,   
			pageNumber:1,
			doPagination:function(pPageIndex, pPageSize) {   
			   //改变opts.pageNumber和opts.pageSize的参数值，用于下次查询传给数据层查询指定页码的数据   
			    var gridOpts = $(theGridID).datagrid('options');   
			    gridOpts.pageNumber = pPageIndex;   
			    gridOpts.pageSize = pPageSize;     
			    loadDataGrid();   
			},    
			
			onLoadSuccess: function(){   
			    //加载完数据关闭等待的div   
			    $(theGridID).datagrid('loaded'); 
			},
			
			frozenColumns : typeof theFrozenColumns != 'undefined' ? theFrozenColumns:
			[
				[
					//{field : 'ck',checkbox : true}
				] 
			],
			
			columns : theColumns,
	
			toolbar : theToolbar,
			
			onClickRow : function(row){
				if (typeof (customOnClickRow) == "function") {
					customOnClickRow(row);
				}
				
			},
			onDblClickRow : function(row){
				if (typeof (customOnDblClickRow) == "function") {
					customOnDblClickRow(row);
				}
				
			}
		});
		
		$(theGridID).datagrid('getPager').pagination({   
			pageSize: 10,//每页显示的记录条数，默认为20  
		    pageList: [10,20,30,40,50],//可以设置每页记录条数的列表  
		    beforePageText: '第',//页数文本框前显示的汉字  
		    afterPageText: '页, 共  {pages} 页',  
		   	displayMsg:'当前显示从 [{from}] 到 [{to}]条记录, 共[{total}]条记录',   
		   	onSelectPage : function(pPageIndex, pPageSize) {   
		       //改变opts.pageNumber和opts.pageSize的参数值，用于下次查询传给数据层查询指定页码的数据   
		       var gridOpts = $(theGridID).datagrid('options');   
		       gridOpts.pageNumber = pPageIndex;   
		       gridOpts.pageSize = pPageSize;     
		       //查询
		       loadDataGrid();  
		    }   
		}); 
		
		loadDataGrid();

		if (window.screen) {              
			//判断浏览器是否支持window.screen判断浏览器是否支持screen   
			var myw = screen.availWidth;   //定义一个myw，接受到当前全屏的宽   
			var myh = screen.availHeight;  //定义一个myw，接受到当前全屏的高   
			window.moveTo(0, 0);           //把window放在左上脚  
			window.resizeTo(myw, myh);     //把当前窗体的长宽跳转为myw和myh   
		}

	}
	
	if(typeof(customOnLoad)=="function") {
    	customOnLoad();
    }
	
	$('body').append('<div id="myWindow" class="easyui-dialog" closed="true"></div>');
	//$('body').append('<div id="p" class="easyui-progressbar" style="width:400px;"></div>');

	$('#myWindow').window({
		onBeforeClose : function() { // 当面板关闭之前触发的事件
			$('#myWindow').window('close',true);
			if(typeof(parent.window.QueryData)=="function") {
				parent.window.QueryData();
			}
			if(typeof theGridID != 'undefined'){
				QueryData();
			}
			else{
				window.parent.location.reload();
			}
		}
	});

	function getWidth(percent){ 
	    return document.body.clientWidth*percent; 
	} 
	
	/**
	 * 指定位置显示$.messager.show
	 * options $.messager.show的options
	 * param = {left,top,right,bottom}
	 */
	$.extend($.messager, {
		showBySite : function(options,param) {
			var site = $.extend( {
				left : "",
				top : "",
				right : 0,
				bottom : -document.body.scrollTop
						- document.documentElement.scrollTop
			}, param || {});
			var win = $("body > div .messager-body");
			if(win.length<=0)
				$.messager.show(options);
			win = $("body > div .messager-body");
			win.window("window").css( {
				left : site.left,
				top : site.top,
				right : site.right,
				zIndex : $.fn.window.defaults.zIndex++,
				bottom : site.bottom
			});
		}
	});

});

$.extend($.fn.datagrid.defaults.view,{
	onAfterRender : function(dd) {
		if(typeof theArgFormAutoShow == 'undefined'){
			$(theArgFormID).appendTo('.datagrid-toolbar');
		}
		else{
			if(theArgFormAutoShow){
				$(theArgFormID).appendTo('.datagrid-toolbar');
			}
		}
		
		resize();
	}
});

$(window).resize(function(){
	resize()
}); 

function resize() {
	if(typeof theGridID != 'undefined'){
		$(theGridID).datagrid('resize', {
			width : typeof theGridWidth != 'undefined' ?theGridWidth:document.body.clientWidth,
			height : typeof theGridHeight != 'undefined' ?theGridHeight:document.body.clientHeight
		});
	}
}

$.fn.serializeObject = function()    
{    
   var o = {};    
   var a = this.serializeArray();    
   $.each(a, function() {    
       if (o[this.name]) {    
           if (!o[this.name].push) {    
               o[this.name] = [o[this.name]];    
           }    
           o[this.name].push(this.value || '');    
       } else {    
           o[this.name] = this.value || '';    
       }    
   });    
   return o;    
}; 

function loading(){
	 $(theGridID).datagrid('loading');//打开等待div  
}

function loaded(){
	$(theGridID).datagrid('loaded');   
}


function loadDataGrid(){  
	 if(typeof(customBeforeQuery)=="function") {
		 customBeforeQuery();
	  }
    $(theGridID).datagrid('loading');//打开等待div   
    var queryCondition = JSON.stringify($(theArgFormID).serializeObject());
    var gridOpts = $(theGridID).datagrid('options');  
    var queryParams =[{pageNumber:gridOpts.pageNumber,pageSize:gridOpts.pageSize,sortName:gridOpts.sortName,sortOrder:gridOpts.sortOrder}]; 
    queryParams = JSON.stringify(queryParams);
    var params = "{queryParams:"+queryParams+",queryCondition:["+queryCondition+"]}";
    //alert(params);
    $.ajax({
          type: "POST",   //访问WebService使用Post方式请求
          contentType: "application/json; charset=utf-8",
          url: postURL, //调用WebService的地址和方法名称组合 ---- WsURL/方法名
          data: params,  //这里是要传递的参数，格式为 data: "{paraName:paraValue}",下面将会看到       
          dataType: 'json',   //WebService 会返回Json类
          success: function(result) {     //回调函数，result，返回值     
        	  if (result.rows.length == 0) {  
        		  //$.messager.alert("结果", "没有数据!", "info", null);  
        		  showMsg('操作提示', '查询结果没有数据!');
        	  }  
        	 
			  $(theGridID).datagrid('loadData', {   
			       "total": result.total,   
			       "rows": result.rows   
			   });   
			 
			  if(typeof(custominit)=="function") {
					custominit(result);
			  }
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) { 
               //alert(errorThrown); 
               window.showMsg('操作提示','查询失败，请重新登录！');
               $(theGridID).datagrid('loaded'); 
              // window.location.reload();
          } 
    });
}  

function getSelected() {
	var selected = $(theGridID).datagrid('getSelected');
	if (selected) {
		alert(selected.code + ":" + selected.name + ":" + selected.addr
				+ ":" + selected.col4);
	}
}

function getSelections() {
	var ids = [];
	var rows = $(theGridID).datagrid('getSelections');
	for ( var i = 0; i < rows.length; i++) {
		ids.push(rows[i].code);
	}
	alert(ids.join(':'));
}

function clearSelections() {
	$(theGridID).datagrid('clearSelections');
}

function selectRow() {
	$(theGridID).datagrid('selectRow', 2);
}

function selectRecord() {
	$(theGridID).datagrid('selectRecord', '002');
}

function unselectRow() {
	$(theGridID).datagrid('unselectRow', 2);
}

function mergeCells() {
	$(theGridID).datagrid('mergeCells', {
		index : 2,
		field : 'addr',
		rowspan : 2,
		colspan : 2
	});
}

function doAdd(w,h,params) {
	var w = w === undefined ? theWinWidth : w ;
	var h = h === undefined ? theWinHeight : h ;
	var params = params === undefined ? "" : params ;
	var title = theGridTitle+"管理 | 新建";
	var url = addURL;
	if(params){
		url += "?" + params;
	}
    showMyWindow(title,url, w, h);
}

function doAddWithParams(params,title,w,h) {
	var w = w === undefined ? theWinWidth : w ;
	var h = h === undefined ? theWinHeight : h ;
	var params = params === undefined ? "" : params ;
	var title = title+"管理 | 新建";
	var url = addURL;
	if(params){
		url += "?" + params;
	}
	if(w>document.body.clientWidth){
		w=document.body.clientWidth;
	}
	if(h>document.body.clientHeight){
		h=document.body.clientHeight;
	}
    showMyWindow(title,url, w, h);
}

function doEdit(params,w,h) {
	var w = w === undefined ? theWinWidth : w ;
	var h = h === undefined ? theWinHeight : h ;
	var title = theGridTitle+"管理 | 编辑";
	var rows = $(theGridID).datagrid('getSelections');
    if (rows.length == 1) {
        showMyWindow(title,editURL+"?"+params, w, h);
    } else {
        //showMsg("温馨提示", "请选择一行！");
        $.messager.alert("提示", "请选择一行"+theGridTitle+"记录!", "info", null);  
    }
}

function doEditWithTitle(params,title,w,h) {
	var w = w === undefined ? theWinWidth : w ;
	var h = h === undefined ? theWinHeight : h ;
	var params = params === undefined ? "" : params ;
	var title = title+"管理 | 编辑";
	var url = editURL;
	if(params){
		url += "?" + params;
	}
	if(w>document.body.clientWidth){
		w=document.body.clientWidth;
	}
	if(h>document.body.clientHeight){
		h=document.body.clientHeight;
	}
	showMyWindow(title,url, w, h);
}

function doEditClick(params,w,h) {
	var w = w === undefined ? theWinWidth : w ;
	var h = h === undefined ? theWinHeight : h ;
	var title = theGridTitle+"管理 | 编辑";
	showMyWindow(title,editURL+"?"+params, w, h);
}

function doDelete(Ids,isClick) {
	var isClick = isClick === undefined ? false:isClick;
	if(!isClick){
		var selectedRow = $(theGridID).datagrid('getSelections'); //获取选中行  
		if(selectedRow.length==0){
			$.messager.alert("提示", "请先选择要删除的"+theGridTitle+"记录!", "info", null);  
			return;
		}
	}
	$.messager.confirm(theGridTitle+'删除确认', '确定要删除吗?', function(row) {
		if (row) {
			$(theGridID).datagrid('loading');//打开等待div
			$.ajax({
				url : deleteURL,
				type : "post",
				cache : false,
				data : "ids=" + Ids,
				success : function(data) {
				    if(data=="success"){
				    	//alert("删除"+theGridTitle+"成功!");
						//$.messager.alert('删除', '操作成功!');
				    	showMsg('操作提示', '删除'+theGridTitle+'成功!');
						loadDataGrid();
						if(typeof(parent.window.QueryData)=="function") {
							parent.window.QueryData();
						}
				    }
				    else{
				    	$.messager.alert('操作提示', '删除'+theGridTitle+'操作失败，'+data+'！','error');
				    }
					$(theGridID).datagrid('loaded');
				}
			});
		}
	})
}

function showMyWindow(title, href, width, height, modal, minimizable, maximizable) {
	var h=document.body.clientHeight;
	var w = document.body.clientWidth-1;
    $('#myWindow').window({
        title: title,
        top  : 0,
        left : 0,
        width: w,//width === undefined ? 600 : width,
        height: h,//height === undefined ? 400 : height,
        content: '<iframe scrolling="yes" frameborder="0"  src="' + href + '" style="width:100%;height:98%;"></iframe>',
        //        href: href === undefined ? null : href,
        modal: modal === undefined ? true : modal,
        minimizable: minimizable === undefined ? false : minimizable,
        maximizable: maximizable === undefined ? false : maximizable,
        shadow: false,
        cache: false,
        closed: false,
        collapsible: false,
        resizable: false,
        loadingMessage: '正在加载数据，请稍等片刻......'
    });
}

function closeMyWindow() {
	$('#myWindow').window('close');
}

function showMsg(title, msg, isAlert) {
	 if (isAlert !== undefined && isAlert) {
	     $.messager.alert(title, msg);
	 } else {
//	     $.messager.show({
//	         title: title,
//	         msg: msg,
//	         showType: 'show'
//	     });
		 showBySite(title, msg);
	 }
}

function showBySite(title,msg) {
	$.messager.showBySite({
		title : title,
		msg : msg,
		showType : 'slide'//slide,fade

	}, {
		top : 0,// 将$.messager.show的top设置为点击对象之下
		left : (document.body.clientWidth/2)-100,  //将$.messager.show的left设置为与点击对象对齐
		bottom : ""
	});
} 

 function deleteConfirm() {                           
     return showConfirm('温馨提示', '确定要删除吗?');
 }                                                   
 function showConfirm(title, msg, callback) {        
     $.messager.confirm(title, msg, function (r) {   
         if (r) {                                    
             if (jQuery.isFunction(callback))        
                 callback.call();                    
         }                                           
     });                                             
 }                                                   
 function showProcess(isShow, title, msg) {          
     if (!isShow) {                                  
         $.messager.progress('close');               
         return;                                     
     }                                               
     var win = $.messager.progress({                 
         title: title,                               
         msg: msg                                    
     });                                             
 }  
